package org.vicesos.lovecompass;

import java.io.IOException;
import java.util.Random;

import javax.microedition.khronos.opengles.GL10;

import org.anddev.andengine.audio.music.MusicFactory;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.particle.ParticleSystem;
import org.anddev.andengine.entity.particle.emitter.PointParticleEmitter;
import org.anddev.andengine.entity.particle.initializer.AccelerationInitializer;
import org.anddev.andengine.entity.particle.initializer.ColorInitializer;
import org.anddev.andengine.entity.particle.initializer.RotationInitializer;
import org.anddev.andengine.entity.particle.initializer.VelocityInitializer;
import org.anddev.andengine.entity.particle.modifier.ExpireModifier;
import org.anddev.andengine.entity.primitive.Rectangle;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.scene.background.SpriteBackground;
import org.anddev.andengine.entity.scene.background.modifier.ColorModifier;
import org.anddev.andengine.entity.scene.menu.MenuScene;
import org.anddev.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener;
import org.anddev.andengine.entity.scene.menu.item.IMenuItem;
import org.anddev.andengine.entity.scene.menu.item.SpriteMenuItem;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.text.Text;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener;
import org.anddev.andengine.entity.scene.Scene.ITouchArea;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.sensor.accelerometer.AccelerometerData;
import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener;
import org.anddev.andengine.ui.activity.LayoutGameActivity;
import org.anddev.andengine.util.Debug;
import org.anddev.andengine.util.HorizontalAlign;


import org.anddev.andengine.entity.IEntity;
import org.anddev.andengine.entity.modifier.AlphaModifier;
import org.anddev.andengine.entity.modifier.DelayModifier;
import org.anddev.andengine.entity.modifier.EntityModifierList;
import org.anddev.andengine.entity.modifier.IEntityModifier.IEntityModifierListener;
import org.anddev.andengine.entity.modifier.LoopEntityModifier;
import org.anddev.andengine.entity.modifier.LoopEntityModifier.ILoopEntityModifierListener;
import org.anddev.andengine.entity.modifier.ParallelEntityModifier;
import org.anddev.andengine.entity.modifier.RotationByModifier;
import org.anddev.andengine.entity.modifier.RotationModifier;
import org.anddev.andengine.entity.modifier.ScaleModifier;
import org.anddev.andengine.entity.modifier.SequenceEntityModifier;


import org.anddev.andengine.util.modifier.IModifier;
import org.anddev.andengine.util.modifier.LoopModifier;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

import org.vicesos.lovecompass.R;

import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PointF;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.widget.RelativeLayout;
import android.widget.Toast;

import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BuildableBitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.region.BaseTextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegion;

import org.anddev.andengine.audio.music.Music;

import android.widget.Toast;

public class LoveCompassActivity extends LayoutGameActivity implements IAccelerometerListener, IOnMenuItemClickListener {

	private static final int CAMERA_WIDTH = 480;
	private static final int CAMERA_HEIGHT = 720;
	
	private Camera mCamera;
	private Engine mEngine;

	private Music mMusic;
	private boolean mSilentMode;
	
	private BitmapTextureAtlas mBitmapTextureAtlasHeart;
	private BitmapTextureAtlas mBitmapTextureAtlasNotes;
	private BitmapTextureAtlas mBitmapTextureAtlasAudioDisabled;
	private BitmapTextureAtlas mBitmapTextureAtlasArrow;
	private BitmapTextureAtlas mBitmapTextureAtlasButtonLove;
	private BitmapTextureAtlas mBitmapTextureAtlasBackground;
	
	private TextureRegion mHeartTextureRegion;
	private TextureRegion mNotesTextureRegion;
	private TextureRegion mArrowTextureRegion;
	private TextureRegion mAudioDisabledTextureRegion;
	private TextureRegion mButtonLoveTextureRegion;
	private TextureRegion mBackgroundTextureRegion;

	private BitmapTextureAtlas mBitmapTextureAtlas;
	private TextureRegion mParticleTextureRegion;
	
	
    private Random mRnd;
	
	private Scene scene;

	private AdView adView;

	private Rectangle Rect;
	
	SharedPreferences settings;
	
	protected MenuScene mMenuScene;

	private BitmapTextureAtlas mMenuTexture;
	protected TextureRegion mMenuBackTextureRegion;
	protected TextureRegion mMenuQuitTextureRegion;
	
	protected static final int MENU_BACK = 0;
	protected static final int MENU_QUIT = MENU_BACK + 1;
	
	
	private boolean arrowfinding = false;
	private int arrowlastposition = 0;
	 @Override
     protected int getLayoutID() {
             return R.layout.main;
     }

     @Override
     protected int getRenderSurfaceViewID() {
             return R.id.xmllayoutexample_rendersurfaceview;
     }
  	public class HeartEntityModifier{
  		
  	};
  	
 	@Override
 	public Engine onLoadEngine() {
 		mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
 		mEngine = new Engine(new EngineOptions(true,ScreenOrientation.PORTRAIT,new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT),mCamera).setNeedsMusic(true));
 		mRnd = new Random();
 		return mEngine;
 	}
    
 	

	@Override 
	protected void onSetContentView() {
		// Create the adView
	    super.onSetContentView();
		
		adView = new AdView(this, AdSize.BANNER, "A14E78589BD1541");
	    
	    AdRequest request = new AdRequest();

	    request.setGender(AdRequest.Gender.FEMALE);

	    request.setBirthday("19850101");
	    
	    request.addTestDevice(AdRequest.TEST_EMULATOR);

	    adView.setGravity(Gravity.CENTER);
	    RelativeLayout layout = (RelativeLayout)findViewById(R.id.finallayout);
	    
	    // Add the adView to it
	    layout.addView(adView);

	    // Initiate a generic request to load it with an ad
	    adView.loadAd(request);
	}
 	
	@Override
	public void onLoadResources() {
		
		
		this.mBitmapTextureAtlasHeart = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mBitmapTextureAtlasArrow = new BitmapTextureAtlas(32, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mBitmapTextureAtlasNotes = new BitmapTextureAtlas(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mBitmapTextureAtlasAudioDisabled = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mBitmapTextureAtlasButtonLove = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mBitmapTextureAtlasBackground = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);

		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");

		this.mHeartTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlasHeart, this, "heart.png", 0, 0);
		this.mNotesTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlasNotes, this, "notes.png", 0, 0);
		this.mArrowTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlasArrow, this, "arrow.png", 0, 0);
		this.mAudioDisabledTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlasAudioDisabled, this, "audio_disabled.png", 0, 0);
		this.mButtonLoveTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlasButtonLove, this, "button_love.png", 0, 0);
		this.mBackgroundTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlasBackground, this, "background.png", 0, 0);
		
//		MusicFactory.setAssetBasePath("mfx/");
//		try {
//			this.mMusic = MusicFactory.createMusicFromAsset(this.mEngine.getMusicManager(), this, "melody.mid");
//			this.mMusic.setLooping(true);
//		} catch (final IOException e) {
//			Debug.e(e);
//		}
		
		this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlasHeart);
		this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlasNotes);
		this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlasArrow);
		this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlasAudioDisabled);
		this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlasButtonLove);
		this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlasBackground);

		this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "particle_heart.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
		
		this.mMenuTexture = new BitmapTextureAtlas(512, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mMenuBackTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mMenuTexture, this, "menu_back.png", 0, 0);
		this.mMenuQuitTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mMenuTexture, this, "menu_quit.png", 0, 100);
		this.mEngine.getTextureManager().loadTexture(this.mMenuTexture);
	    
		settings = getSharedPreferences("PREFS_NAME", 0);
        mSilentMode = settings.getBoolean("silentMode", false);
        

   
	}
 	
	@Override
	public Scene onLoadScene() {
		this.mEngine.registerUpdateHandler(new FPSLogger());
		
		this.createMenuScene();
	
		scene = new Scene();


		final int x_heart = (CAMERA_WIDTH - this.mHeartTextureRegion.getWidth()) / 2;
		final int y_heart = (CAMERA_HEIGHT - this.mHeartTextureRegion.getHeight()) / 2;
		final int x_arrow = (CAMERA_WIDTH - this.mArrowTextureRegion.getWidth()) / 2;
		final int y_arrow = (CAMERA_HEIGHT - this.mArrowTextureRegion.getHeight()) / 2;
		final int x_notes = CAMERA_WIDTH-(this.mNotesTextureRegion.getWidth()*2)-20;
		final int y_notes = 100;
		final int x_audiodisabled = CAMERA_WIDTH-(this.mNotesTextureRegion.getWidth()*2)-20;
		final int y_audiodisabled = 100;
		final int x_buttonlove = (CAMERA_WIDTH - this.mButtonLoveTextureRegion.getWidth()) / 2;
		final int y_buttonlove = CAMERA_HEIGHT - this.mButtonLoveTextureRegion.getHeight() - 50;
		final int x_background = 0;
		final int y_background = 0;

		final Sprite background = new Sprite(x_background, y_background, this.mBackgroundTextureRegion);	
		background.setScaleCenter(0, 0);
		background.setScale(2.82f);
		scene.setBackground(new SpriteBackground(background));	
				
		
		final Sprite heart = new Sprite(x_heart, y_heart, this.mHeartTextureRegion);
		final Sprite notes = new Sprite(x_notes, y_notes , this.mNotesTextureRegion);		
		final Sprite arrow = new Sprite(x_arrow, y_arrow, this.mArrowTextureRegion);
		final Sprite buttonlove = new Sprite(x_buttonlove, y_buttonlove, this.mButtonLoveTextureRegion);
		final Sprite audiodisabled = new Sprite(x_audiodisabled, y_audiodisabled, this.mAudioDisabledTextureRegion);
		
		
		final SequenceEntityModifier entityHeartModifier = new SequenceEntityModifier(
				new IEntityModifierListener() {
					@Override
					public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) {
						LoveCompassActivity.this.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								//Toast.makeText(LoveCompassActivity.this, "Sequence started.", Toast.LENGTH_LONG).show();
								pModifier.setRemoveWhenFinished(false);
							}
						});
					}

					@Override
					public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) {
						LoveCompassActivity.this.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								//Toast.makeText(LoveCompassActivity.this, "Sequence finished."+pEntityModifier.isRemoveWhenFinished(), Toast.LENGTH_LONG).show();
								pEntityModifier.reset();
							}
						});
					}
				},
				new ScaleModifier(2, 2.3f, 2.5f),
				new ScaleModifier(2, 2.5f, 2.3f)
				
		);				
		final SequenceEntityModifier entityArrowModifier = new SequenceEntityModifier(
				new IEntityModifierListener() {
					@Override
					public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) {
						LoveCompassActivity.this.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								pModifier.setRemoveWhenFinished(false);
							}
						});
					}

					@Override
					public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) {
						LoveCompassActivity.this.runOnUiThread(new Runnable() {
							@Override
							public void run() {							
								pEntityModifier.reset();
							}
						});
					}
				},
				new RotationModifier(0.4f, -4, 4),
				new RotationModifier(0.4f, 4, -4)
				
		);	
		

		heart.registerEntityModifier(entityHeartModifier);
		//arrow.registerEntityModifier(new ScaleModifier(0, 1.0f, 2.0f));
		
		
		scene.registerTouchArea(notes);
		scene.registerTouchArea(buttonlove);

		
		
		scene.setOnAreaTouchListener(new IOnAreaTouchListener() {
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
				if(pTouchArea == buttonlove ){
					if (LoveCompassActivity.this.arrowfinding == false){
						int arrownewposition = mRnd.nextInt() % (360*5);
						final SequenceEntityModifier entityArrowFindModifier = new SequenceEntityModifier(
								new IEntityModifierListener() {
									@Override
									public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) {
										LoveCompassActivity.this.runOnUiThread(new Runnable() {
											@Override
											public void run() {
												LoveCompassActivity.this.arrowfinding = true;
												buttonlove.setVisible(false);
											}
										});
									}
									@Override
									public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) {
										LoveCompassActivity.this.runOnUiThread(new Runnable() {
											@Override
											public void run() {							
												LoveCompassActivity.this.arrowfinding = false;
												buttonlove.setVisible(true);
											}
										});
									}
								},
								new RotationModifier(3.5f, arrowlastposition, arrownewposition)
						);	
						arrowlastposition = arrownewposition;
						arrow.registerEntityModifier(entityArrowFindModifier);
					}
				}
				else if ( pTouchArea == notes ){
					if(pSceneTouchEvent.isActionDown()) 
					{				
						if(!mSilentMode) {
							mMusic.pause();
							audiodisabled.setVisible(true);
							mSilentMode = true;
						} else {
							mMusic.play();
							audiodisabled.setVisible(false);
							mSilentMode = false;
						}	
					}
				}
				return true;
			}
		});		
		
	

		
		
		final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter((CAMERA_WIDTH/2), CAMERA_HEIGHT), 2, 5, 200, this.mParticleTextureRegion);

		//particleSystem.addParticleInitializer(new VelocityInitializer(4, 22, -60, -90));

		particleSystem.addParticleInitializer(new VelocityInitializer(40, -40 , -60, -90));
		
		particleSystem.addParticleInitializer(new AccelerationInitializer(0, 10));
		particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f));
		particleSystem.addParticleInitializer(new ColorInitializer(1.0f, 1.0f, 1.0f));
		particleSystem.addParticleInitializer(new org.anddev.andengine.entity.particle.initializer.ScaleInitializer(1.0f, 2.0f));
		
//		import org.anddev.andengine.entity.particle.modifier.ScaleModifier;

//		particleSystem.addParticleModifier(new org.anddev.andengine.entity.particle.modifier.ScaleModifier(0.5f, 2.0f, 0, 5));
		particleSystem.addParticleModifier(new ExpireModifier(11.5f));
		particleSystem.addParticleModifier(new org.anddev.andengine.entity.particle.modifier.AlphaModifier(1.0f, 0.5f, 2.5f, 6.5f));
//		particleSystem.addParticleModifier(new org.anddev.andengine.entity.particle.modifier.AlphaModifier(0.0f, 1.0f, 3.5f, 4.5f));
//		particleSystem.addParticleModifier(new org.anddev.andengine.entity.particle.modifier.ColorModifier(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 11.5f));
//		particleSystem.addParticleModifier(new org.anddev.andengine.entity.particle.modifier.AlphaModifier(1.0f, 0.0f, 4.5f, 11.5f));

		
		
		
		
		//heart.setScale(2.5f);
		
		notes.setScale(2.0f);
		audiodisabled.setScale(2.0f);
		arrow.setScale(1.7f);

		scene.attachChild(particleSystem);
		scene.attachChild(heart);
		scene.attachChild(arrow);
		scene.attachChild(notes);
		scene.attachChild(audiodisabled);
		scene.attachChild(buttonlove);
//		this.mMusic.play();
		if(mSilentMode){
//			this.mMusic.stop();
			audiodisabled.setVisible(true);
		}
		else{
//			this.mMusic.play();
			audiodisabled.setVisible(false);			
		}
		
		
		return scene;
	}
	
	@Override
	public void onLoadComplete() {
    
	}
	
	
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		
	}

	@Override
	public void onWindowFocusChanged(boolean pHasWindowFocus) {
		// TODO Auto-generated method stub
		super.onWindowFocusChanged(pHasWindowFocus);
		if(pHasWindowFocus){
			if(mSilentMode){
				MusicFactory.setAssetBasePath("mfx/");
				try {
					this.mMusic = MusicFactory.createMusicFromAsset(this.mEngine.getMusicManager(), this, "melody.mid");
					this.mMusic.setLooping(true);
				} catch (final IOException e) {
					Debug.e(e);
				}
				this.mMusic.play();
				this.mMusic.pause();				
			}
			else{
				MusicFactory.setAssetBasePath("mfx/");
				try {
					this.mMusic = MusicFactory.createMusicFromAsset(this.mEngine.getMusicManager(), this, "melody.mid");
					this.mMusic.setLooping(true);
				} catch (final IOException e) {
					Debug.e(e);
				}
	
				this.mMusic.play();
			}
			
		}
		else{
			mMusic.stop();
		}
	}
	
	@Override
	public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) {
		if((pKeyCode == KeyEvent.KEYCODE_MENU || pKeyCode == KeyEvent.KEYCODE_BACK ) && pEvent.getAction() == KeyEvent.ACTION_DOWN) {
			if(this.scene.hasChildScene()) {
				/* Remove the menu and reset it. */
				this.mMenuScene.back();
			} else {
				/* Attach the menu. */
				Rect.setColor(0.0f, 0.0f, 0.0f); // Whatever colour you fancy
				Rect.setAlpha(0.5f);
				this.scene.setChildScene(this.mMenuScene, false, true, true);
			}
			return true;
		} else {
			return super.onKeyDown(pKeyCode, pEvent);
		}
		
	}

	@Override
	public boolean onMenuItemClicked(final MenuScene pMenuScene, final IMenuItem pMenuItem, final float pMenuItemLocalX, final float pMenuItemLocalY) {
		switch(pMenuItem.getID()) {
			case MENU_BACK:
				this.mMenuScene.back();
				return true;
			case MENU_QUIT:
				/* End Activity. */
				this.finish();
				return true;
			default:
				return false;
		}
	}

	protected void createMenuScene() {
		this.mMenuScene = new MenuScene(this.mCamera);

		Rect = new Rectangle(0,0, CAMERA_WIDTH, CAMERA_HEIGHT);
		Rect.setColor(0.0f, 0.0f, 0.0f); // Whatever colour you fancy
		Rect.setAlpha(0.5f);       
		
		this.mMenuScene.attachChild(Rect);
		this.mMenuScene.setBackgroundEnabled(false);
		
		final SpriteMenuItem backMenuItem = new SpriteMenuItem(MENU_BACK, this.mMenuBackTextureRegion);
		backMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		this.mMenuScene.addMenuItem(backMenuItem);	
			
		final SpriteMenuItem quitMenuItem = new SpriteMenuItem(MENU_QUIT, this.mMenuQuitTextureRegion);
		quitMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		this.mMenuScene.addMenuItem(quitMenuItem);

		this.mMenuScene.buildAnimations();

		this.mMenuScene.setOnMenuItemClickListener(this);
	}

	@Override
	public void onAccelerometerChanged(AccelerometerData pAccelerometerData) {		
	}
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		
       // We need an Editor object to make preference changes.
       // All objects are from android.context.Context
       settings = getSharedPreferences("PREFS_NAME", 0);
       SharedPreferences.Editor editor = settings.edit();
       editor.putBoolean("silentMode", mSilentMode);

       // Commit the edits!
       editor.commit();
	}
}
